#include <stdlib.h>
#include <stdio.h>
#include <gdbm.h>

#define WLDB_RECORD_SIZE 16
#define WLDB_ID_SIZE 8
#define LOCKY_CODE_SIZE 8

#define GDBM_BLOCK_SIZE 512
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

int locky_code_equals(code1, code2)
     char *code1;
     char *code2;
{
  int i;
  for (i = 0; i < LOCKY_CODE_SIZE; i++) {
    if (code1[i] != code2[i]) {
      return FALSE;
    }
  }
  return TRUE;
}

void convertToGDBM (file)
     char *file;
{
  char record[WLDB_RECORD_SIZE];
  char hashedID[WLDB_ID_SIZE];
  char lockyCode[LOCKY_CODE_SIZE];

  GDBM_FILE dbf;
  datum key, data;
  datum result;
  int count = 0;
  int mod_count = 0;
  int new_count = 0;
  int uc_count = 0;

  if ((dbf = gdbm_open ("locky.dbm", GDBM_BLOCK_SIZE,
			GDBM_WRCREAT | GDBM_FAST, 0700, NULL)) == NULL) {
    fprintf (stderr, "error: %s\n", gdbm_strerror (gdbm_errno));
    exit(1);
  }
  FILE *fp = fopen (file, "r");
  int read = fread (record, sizeof(char), WLDB_RECORD_SIZE, fp);
  while (read == WLDB_RECORD_SIZE) {
    int i = 0;
    for (i = 0; i < WLDB_ID_SIZE; i++) {
      hashedID[i] = record[i];
    }
    for (i = 0; i< LOCKY_CODE_SIZE; i++) {
      lockyCode[i] = record[WLDB_ID_SIZE + i];
    }
    key.dsize = WLDB_ID_SIZE;
    key.dptr = hashedID;
    data.dsize = LOCKY_CODE_SIZE;
    data.dptr = lockyCode;
    count++;
    // result.dptr is malloc-ed.
    result.dptr = NULL;
    result = gdbm_fetch (dbf, key);
    if (result.dptr == NULL) {
      new_count++;
      gdbm_store (dbf, key, data, GDBM_INSERT);
    }
    else {
      if (!locky_code_equals(result.dptr, data.dptr)) {// exists but modified
	mod_count++;
	gdbm_store (dbf, key, data, GDBM_REPLACE);
      }
      else { // exists and unchanged
	uc_count++;
      }
      free (result.dptr);
    }
    if (count % 1000 == 0) {
      fprintf (stdout, "%d entries, %d new, %d modified, %d unchanged\n",
	       count, new_count, mod_count, uc_count);
    }
    if (count % 100000 == 0) {
      gdbm_sync(dbf);
    }
    read = fread (record, sizeof(char), WLDB_RECORD_SIZE, fp);
  }
  gdbm_close (dbf);
  fclose (fp);
}

int
main (argc, argv)
     int argc;
     char **argv;
{
  if (argc != 2) {
    fprintf (stderr, "Usage: locky2gdbm default.wldb");
    exit(1);
  }
  char *file = argv[1];
  convertToGDBM(file);
  exit(0);
}
